import { Component, OnInit,AfterViewInit,Output,Input,EventEmitter,ViewChild,ElementRef } from '@angular/core';
import { Subject,Unsubscribable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { NavController,ModalController } from '@ionic/angular';
import { AppNotification } from '@global/service/Notification';
import { App } from '@global/service/App';
import { Http } from '@global/service/Http';
import { ComUtil } from '@global/util/ComUtil';
import { AppEnvironment } from 'src/environments/AppEnvironment';

import { WFWorkListMobMDViewPage } from '@pages/demo/wfwork-list-mob-mdview/wfwork-list-mob-mdview.page';
import { AppDashboardViewPage } from '@pages/demo/app-dashboard-view/app-dashboard-view.page';

import EditViewEngine from 'src/engine/view/edit-view-engine';
import { EditForm } from '@widget/org-user/user-info-form-form/user-info-form-form';
import { Righttoolbar } from '@widget/org-user/mob-edit-viewrighttoolbar-toolbar/mob-edit-viewrighttoolbar-toolbar';

@Component({
  selector: 'view-org-user-mob-edit-view',
  templateUrl: './org-user-mob-edit-view.page.html',
  styleUrls: ['./org-user-mob-edit-view.page.scss']
})
export class OrgUserMobEditViewPage implements OnInit,AfterViewInit {

    /**
     * 子组件EditForm
     *
     * @public
     * @type {Subject}
     * @memberof OrgUserMobEditView
     */
    @ViewChild(EditForm)
    private form: EditForm;

    /**
     * 子组件Righttoolbar
     *
     * @public
     * @type {Subject}
     * @memberof OrgUserMobEditView
     */
    @ViewChild(Righttoolbar)
    private righttoolbar: Righttoolbar;

    /**
     * 视图订阅对象
     *
     * @public
     * @type {Subject}
     * @memberof OrgUserMobEditView
     */
    public viewState: Subject<ViewState> = new Subject();

    /**
     * 路由传递参数
     *
     * @public
     * @type {void}
     * @memberof OrgUserMobEditView
     */
    public $route ={};

    /**
     * 当前视图激活数据
     *
     * @public
     * @type {void}
     * @memberof OrgUserMobEditView
     */
    public $activeData:Array<any> =[];

    /**
     * 是否为模态框弹出
     *
     * @memberof OrgUserMobEditView
     */
    @Input() isModalMode:boolean =false;

    /**
     * 是否嵌入分页导航视图
     *
     * @memberof TestEntity2MobPickupView
     */
    @Input() isTabexp:boolean =false;

    /**
     * 视图值变化事件
     *
     * @public
     * @type {EventEmitter}
     * @memberof OrgUserMobEditView
     */    
    @Output() public viewdataschange =new EventEmitter();

    /**
     * 视图参数
     *
     * @public
     * @type {Subject}
     * @memberof OrgUserMobEditView
     */
    @Input() public viewdata:any;

    /**
     * 父数据对象
     *
     * @protected
     * @type {*}
     * @memberof OrgUserMobEditView
     */
    protected srfparentdata: any = {};

    /**
     * 是否为内敛视图
     *
     * @public
     * @type {EventEmitter}
     * @memberof OrgUserMobEditView
     */ 
    @Input() public isembeddedView:boolean =false;

    /**
     * 视图值加载完成事件
     *
     * @public
     * @type {EventEmitter}
     * @memberof OrgUserMobEditView
     */ 
    @Output() public viewload =new EventEmitter();

    /**
     * 视图的关联试图Map
     *
     * @public
     * @type {Map}
     * @memberof OrgUserMobEditView
     */
    public RefViewMap =new Map();

    /**
     * 视图引擎
     *
     * @private
     * @type {Engine}
     * @memberof OrgUserMobEditView
     */
    private engine: EditViewEngine = new EditViewEngine();

    /**
     * 引擎初始化
     *
     * @private
     * @memberof OrgUserMobEditView
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            form: this.form,
        });
    }


     /**
     * angular生命周期(在ngOnInit之后)
     *
     * @memberof OrgUserMobEditView
     */
    public ngAfterViewInit(){
        this.engineInit();
        
        this.registerRefView();
    }

       /**
    * 保存并关闭
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof OrgUserMobEditView
    */
    public SaveAndExit(args: any[], params?: any, $event?: any, xData?: any) {
        const _this: any = this;
        if (!xData || !(xData.save instanceof Function)) {
            if (_this && _this.save instanceof Function) {
                _this.save(args).then((response: any) => {
                    if (!response) {
                        return;
                    } else {
                        _this.$activeData = [{ ...response }];
                        _this.backView();
                        return;
                    }
                });
            }
            return;
        }
        xData.save().then((response: any) => {
            if (!response) {
                return ;
            }
            if (_this.viewdata) {
                _this.viewdataschange.emit([{ ...response }]);
            }
            _this.$activeData =[{ ...response }];
            _this.backView();
        });
    }
        /**
    * 开始流程
    *
    * @param {*} [arg={}]
    * @param {*} [params]
    * @memberof OrgUserMobEditView
    */
    public SaveAndStart(args: any[], params?: any, $event?: any, xData?: any) {
        const _this: any = this;
        Object.assign(args[0],{iscancelnotice:true});
        if (!xData || !(xData.save instanceof Function)) {
            if (_this && _this.save instanceof Function) {
                _this.save(args[0]).then((response: any) => {
                    if (!response) {
                        return;
                    } else {
                        _this.$activeData = [{ ...response }];
                        _this.startWorkFlow(response).then((res:any) =>{
                            if(!res){
                                return;
                            }else{
                                _this.backView();
                                return;
                            }
                        });
                    }
                });
            }
            return;
        }
        xData.save(args[0]).then((response: any) => {
            if (!response) {
                return ;
            }
            if (_this.viewdata) {
                _this.viewdataschange.emit([{ ...response }]);
            }
            _this.$activeData =[{ ...response }];
            xData.startWorkFlow(response).then((res:any) =>{
                if(!res){
                    return;
                }else{
                    _this.backView();
                    return;
                }
            });
        });
    }

    /**
     * form 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public form_save($event: any, $event2?: any) {
        this.engine.onCtrlEvent('form', 'save', $event);
    }

    /**
     * form 部件 remove 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public form_remove($event: any, $event2?: any) {
        this.engine.onCtrlEvent('form', 'remove', $event);
    }

    /**
     * form 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public form_load($event: any, $event2?: any) {
        this.engine.onCtrlEvent('form', 'load', $event);
    }

    /**
     * righttoolbar 部件 click 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof TestEntityEditView
     */
    public righttoolbar_click($event: any, $event2?: any) {
        if (Object.is($event.tag, 'tbitem1')) {
            this.righttoolbar_tbitem1_click($event, '', $event2);
        }
        if (Object.is($event.tag, 'deuiaction1')) {
            this.righttoolbar_deuiaction1_click($event, '', $event2);
        }
    }


    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof OrgUserMobEditView
     */
    public righttoolbar_tbitem1_click(params: any = {}, tag?: any, $event?: any) {
        // 参数

        // 取数
        let datas: any[] = [];
        let xData: any = null;
        const paramJO = {};
        xData = this.form;
        datas = [...xData.getDatas()];
        // 界面行为
        this.SaveAndExit(datas, paramJO,  $event, xData);
    }
    /**
     * 部件逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @memberof OrgUserMobEditView
     */
    public righttoolbar_deuiaction1_click(params: any = {}, tag?: any, $event?: any) {
        // 参数

        // 取数
        let datas: any[] = [];
        let xData: any = null;
        const paramJO = {};
        xData = this.form;
        datas = [...xData.getDatas()];
        // 界面行为
        this.SaveAndStart(datas, paramJO,  $event, xData);
    }

    /**
     * 返回
     *
     * @memberof OrgUserMobEditView
     */
    public backView() {
        let res:any;
        if(this.isModalMode){
            if(this.$activeData && this.$activeData.length >0){
                res = { ret: 'OK', result:this.$activeData };
            }else{
                res = { ret: 'NO', result:[] };
            }
            this.$modalCtrl.dismiss(res, 'close');
        }else{
            this.$navCtrl.back();
            if(this.$activeData && this.$activeData.length >0){
                res = { ret: 'OK', result:this.$activeData };
            }else{
                res = { ret: 'NO', result:[] };
            }
            this.$app.closeCallback(res);
        }
    }

    /**
     * 嵌入视图点击更多
     *
     * @public
     * @memberof OrgUserMobEditView
     */
    public async click_more(){
        let leftopts:Array<any> =[
    ];
        let rightopts:Array<any> =[
        {text:'保存',id:'righttoolbar_tbitem1'},
    ];
        let opts:Array<any>=leftopts.concat(rightopts);
        const result: string = await this.$app.openActionSheet({items:opts});
        let _this =this;
        if(result.startsWith('righttoolbar')){
            if(_this && _this.righttoolbar_click && _this.righttoolbar_click instanceof Function){
                let firstIndex = result.indexOf('_');
                _this.righttoolbar_click({tag:result.substring(firstIndex + 1)});
            }
        }
    }

    /**
     * 点击toolbar的操作组事件
     *
     * @public
     * @memberof OrgUserMobEditView
     */
    public  async openActionSheet(data:any){

        
    }

    /**
     * 注册关联视图
     *
     * @public
     * @memberof OrgUserMobEditView
     */    
    public registerRefView(){
        this.RefViewMap.set('WFWorkListMobMDView',WFWorkListMobMDViewPage);
        this.RefViewMap.set('AppDashboardView',AppDashboardViewPage);
    }   

    


    /**
     * meditview9状态下发变量
     *
     * @memberof OrgUserMobEditView
     */
    @Input() public panelState:Subject<ViewState> = new Subject();


    /**
     * 实例化对象
     *
     * @memberof OrgUserMobEditView
     */
    constructor(public $http:Http,public $navCtrl: NavController, public $notification: AppNotification, public $activatedRoute: ActivatedRoute,public $modalCtrl:ModalController,public $app:App) {
         this.$activatedRoute.queryParams.subscribe(params => {
         this.$route ="";
         if(params){
            this.$route =JSON.stringify(params);
        }
        })
    }

    /**
     * angular生命周期(组件初始化)
     *
     * @memberof OrgUserMobEditView
     */
    public ngOnInit() {
        if(this.panelState){
            this.panelState.subscribe((res) =>{
            if(Object.is(res.tag,'meditviewpanel')){
                if(Object.is(res.action,'save')){
                    this.viewState.next({ tag:'form', action: 'save', data:res.data });
                }
                if(Object.is(res.action,'remove')){
                    this.viewState.next({ tag:'form', action: 'remove', data:res.data });
                }
            }
        });
        }
    }

    /**
     * 编辑视图返回
     *
     * @memberof OrgUserMobEditView
     */
    public editBackView() {
        if (this.form.$data.ismodify === true) {
            this.$notification.confirm('表单数据已经修改，确定要关闭？').then((res) => {
                if (res) {
                    this.backView();
                }
            })
        } else {
            this.backView();
        }
    }

}